package com.tiny.climber;

import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

import com.tiny.core.game.util.MovimentCalculator;
import com.tiny.core.input.KeyboardManager;
import com.tiny.core.physics.PhysicGameObject;
import com.tiny.core.resources.ImageManager;
import com.tiny.core.resources.SpriteAnimation;
import com.tiny.core.resources.utils.ImageUtils;

public class TinyClimber extends PhysicGameObject {

    private SpriteAnimation spriteAnimation;
    private BufferedImage tinyjump;

    private BufferedImage toRender;
    private boolean right;

    public TinyClimber(int x, int y, MovimentCalculator calc, ImageManager manager) {
        super(x, y, 80, 80, calc);
        BufferedImage loadImage = manager.loadImage("img/climber.png");
        spriteAnimation = ImageUtils.loadSpriteAnimation(loadImage, 8);
        spriteAnimation.setSpeed(20);
        tinyjump = manager.loadImage("img/tiny-jump.png");
        toRender = spriteAnimation.getImage();
        right = true;
    }

    @Override
    public void onUpdate(int currentTick) {
        if (isCollingBelow() && getCollingBelow() instanceof Plataform) {
            setOnGround(true);
            fixCollidingPosition();
            getVelocity().setY(0);
            toRender = spriteAnimation.getImage();
        } else {
            setOnGround(false);
        }

        if (KeyboardManager.getInstance().isHold(KeyEvent.VK_RIGHT) && !(getCollingRight() instanceof Plataform)) {
            getVelocity().setX(400);
            spriteAnimation.setFliped(false);
            right = true;
        } else if (KeyboardManager.getInstance().isHold(KeyEvent.VK_LEFT) && !(getCollingLeft() instanceof Plataform)) {
            getVelocity().setX(-400);
            spriteAnimation.setFliped(true);
            right = false;
        } else {
            getVelocity().setX(0);
            spriteAnimation.startAgain();
        }

        if (KeyboardManager.getInstance().isPressed(KeyEvent.VK_SPACE) && isOnGround()) {
            getVelocity().setY(-700);
        }

        if (isCollingAbove() && getCollingAbove() instanceof Plataform) {
            getVelocity().setY(0);
            fixCollidingPosition();
        }

        if (!isStopped() && isOnGround()) {
            spriteAnimation.update(currentTick);
            toRender = spriteAnimation.getImage();
        } else if (!isOnGround()) {
            if (right) {
                toRender = tinyjump;
            } else {
                toRender = ImageUtils.flipImageX(tinyjump);
            }
        }
    }

    @Override
    public void render(Graphics2D g) {
        g.drawImage(toRender, null, (int) pos.x, (int) pos.y);
    }
}
